import json
import re

import jsonpath
import datetime
import random
import base64
import rsa
import requests
from urllib import parse
from testapp.common.operatorDB import OpeartorDB
from testapp.common.parameteriZation import Paramete, analyzing_param, Manageattr
from testapp.common.sendApirequest import SendApirequests
from testapp.common.sendEmail import SendMail
from testapp.common.sendMsg import SendMsg
from testapp.common.sendDDMsg import SendDDMsg
from testapp.common.readexcels import Readexcel
from testapp.control.ctmanage import CtManage





class CommKeyword(object):
    def __init__(self):
        self.mangerattr = Manageattr()
        self.operatordb = OpeartorDB()
        self.sendApi = SendApirequests()
        self.sendMail = SendMail()
        self.sedMsg = SendMsg()
        self.dingMsg = SendDDMsg()
        self.manage = CtManage()






    def send_api(self, **kwargs):
        """
        发送用例请求 post, get
        :param kwargs:  请求的参数 ，有url,headers,data等
        :return:  bl, cases 一参数返回成功与否，二参数请求结果或失败原因
        """
        try:
            _isOK, url = self.replacedata(data=kwargs['url'])
            method = kwargs['apimethod']
            if kwargs['headers'] is None or kwargs['headers'] == '':
                headers = None
            else:
                _isOk, result = self.format_headers(self.replacedata(data=kwargs['headers'])[1])
                if _isOk:
                    headers = result
                else:
                    return _isOk, result

            if kwargs['body'] is not None:
                try:
                    jsondata = json.loads(self.replacedata(data=kwargs['body'])[1])
                    data = None
                except ValueError:
                    _isOK, data = self.replacedata(data=kwargs['body'])
                    jsondata = None
            else:
                data = None
                jsondata = None
            response = self.sendApi.request_Obj(method=method, url=url, json=jsondata, data=data, headers=headers)
        except Exception as e:
            return False, '发送请求失败' + str(e)
        return True, response








    def set_common_param(self, key, value):
        """
        :param key:  公共变量名
        :param value: 参数
        :return:
        """
        self.mangerattr.setattr(Paramete, analyzing_param(key), value)

    def get_commom_param(self, key):
        """
        :param key: 公共变量名
        :return: 取变量值
        """
        return getattr(Paramete, key)


    def get_json_value_as_key(self, *args, **kwargs):
        """
        得到json中key对应的value,存变量param
        默认传的参数为：
        result:用来接收结果的变量
        method:调用的方法 ，带不带${    } 都行
        param_x:参数，数量不限。格式可为${    }会替换为已存在的数据
        """
        try:
            param = kwargs['result']
            jsonstr = kwargs['f_params']
            key = kwargs['s_params']
        except KeyError:
            return False, '方法缺少参数，执行失败'

        param = analyzing_param(param)
        _isOK, jsonstr = self.replacedata(data=jsonstr)
        _isOK, key = self.replacedata(data=key)

        if param is None or jsonstr is None or key is None:
            return False, '传入的参数为空，执行失败'
        try:
            result = json.loads(jsonstr, strict=False)
        except Exception:
            return False, '传入字典参数格式错误，执行失败'
        ekey = '$..' + key
        try:
            value = str(jsonpath.jsonpath(result, ekey)[0])
        except Exception:
            return False, '字典中[' + jsonstr + ']没有键[' + key + '], 执行失败'
        self.mangerattr.setattr(param, value)
        return True, '已经取得JSON串['+ jsonstr +']中键[' + key + ']的值[' + value + ']==>[${' + param + '}]'



    def get_response_as_key(self, *args, **kwargs):
        """
        得到json中key对应的value,存变量param
        默认传的参数为：
        result:用来接收结果的变量
        method:调用的方法 ，带不带${    } 都行
        param_x:参数，数量不限。格式可为${    }会替换为已存在的数据
        """
        try:
            param = kwargs['result']

            key = kwargs['f_params']
        except KeyError:
            return False, '方法缺少参数，执行失败'

        param = analyzing_param(param)
        _isOK, jsonstr = self.replacedata(data='${response}')
        _isOK, key = self.replacedata(data=key)

        if param is None or jsonstr is None or key is None:
            return False, '传入的参数为空，执行失败'
        try:
            result = json.loads(jsonstr, strict=False)
        except Exception:
            return False, '传入字典参数格式错误，执行失败'
        ekey = '$..' + key
        try:
            value = str(jsonpath.jsonpath(result, ekey)[0])
        except Exception:
            return False, '返回接口果没有键[' + key + '], 执行失败'
        self.mangerattr.setattr(param, value)
        return True, '已经从返回接果中取得键[' + key + ']的值[' + value + ']==>[${' + param + '}]'



    def format_headers(self, param):
        """
        格式化请求头
        :param param:excel里读出出来的header，是从浏览器f12里直接copy的
        :return:
        """
        if param is None:
            return False, 'Headers为空'
        list_header = param.split('\n')
        headers = {}

        for li in list_header:
            buff = li.split(':')
            try:
                headers[buff[0]] = buff[1].lstrip()
            except IndexError:
                return False, 'Headers格式不对'
        return True, headers


    def set_variable(self, **kwargs):
        """
        设置变量
        :param kwargs:
        :return:
        """
        try:
            var = kwargs['result']
            par = kwargs['f_params']
        except KeyError:
            return False, '【设置变量】执行失败：方法缺少【参数一】'
        if par == '':
            return False, '【设置变量】执行失败：传入的【参数一】为空'
        if var == '':
            return False, '【设置变量】执行失败：传入的【变量】为空'

        if type(par) == int:
            param = str(par)
        else:
            param = par
        self.mangerattr.setattr(analyzing_param(var), param)
        return True, ' 已经设置变量[' + param + ']==>[${' + var + '}]'


    def execut_sql(self, **kwargs):
        """
        执行SQL
        :param kwargs:
        :return:
        """
        try:
            sql = kwargs['f_params']
        except KeyError:
            return False, '【执行SQL】执行失败：方法缺少【参数一】SQL语句，执行失败'
        try:
            var = kwargs['result']
            par = kwargs['s_params']
        except Exception:
            var = None
        if (var == '' and par != '') or (var != '' and par == ''):
            return False, '【执行SQL】执行失败：方法【变量】与【参数二】，必须都填或都不填，不能只填一个'
        if var == '':
            var = None
        try:
            dbn = kwargs['t_params']
        except KeyError:
            dbn = None
        env_id = kwargs['envid']
        isOK, result = self.manage.get_data_conf_info(env_id, 1, dbn)   #1代表是mysql, 获取sql的数据库
        if isOK:
            sql = self.mangerattr.replace_data(sql)
            isOK, result = self.operatordb.excetSql(sql, **result)
            if isOK and var is not None:
                data = str(result[par])
                self.mangerattr.setattr(analyzing_param(var), data)
                return True, '执行SQL:[' + sql + ']成功，取得' + par + '的数据[' + data + ']==>[${' + var + '}]'
            elif isOK and var is None and ('insert' in sql.lower() or 'update' in sql.lower() and 'update_time' not in sql.lower()):
                return True, '执行SQL:[' + sql + ']成功'
            elif isOK and var is None:
                res_str = '执行SQL:[' + sql + ']成功;;'
                for key, value in result.items():
                    self.mangerattr.setattr(key, str(value))
                    res_str += '取得[' + str(value) + ']==>[${' + key + '}];'
                return True, res_str
            elif isOK is False:
                return isOK, '执行SQL失败，具体原因：【{}】'.format(result)
        else:
            return isOK, '执行SQL失败，具体原因：【{}】'.format(result)


    def execut_mdx(self, **kwargs):
        """
        执行MDX
        """
        try:
            mdx = kwargs['f_params']
        except KeyError:
            return False, '【执行MDX】执行失败:方法缺少参数一'
        if mdx == '':
            return False, '【执行MDX】执行失败:方法缺少参数一'
        try:
            var = kwargs['result']
            keys = kwargs['s_params']
        except Exception:
            var = None
        if var == '':
            var = None
        try:
            dbn = kwargs['t_params']
        except KeyError:
            dbn = None
        env_id = kwargs['envid']
        isOK, result = self.manage.get_data_conf_info(env_id, 3, dbn)
        if isOK:
            if keys != '':
                result['db'] = result['db'].replace('*', keys)
            result['mdx'] = mdx
            isOK, res = self.operatordb.get_ibmcdata(**result)
            if isOK and var is not None:
                lst = []
                for r in res:
                    lst.append(float(r[keys]))
                self.mangerattr.setattr(analyzing_param(var), str(lst))
                return True, '执行MDX:[' + mdx + ']成功，取得' + keys + '的数据[' + str(lst)[0: 35] + '...' + ']==>[${' + var + '}]'
            elif isOK and var is None:
                res_str = '执行MDX:[' + mdx + ']成功;;'
                keyslst = keys.split(',')
                for key in keyslst:
                    lst = []
                    for r in res:
                        lst.append(float(r[key]))
                    self.mangerattr.setattr(analyzing_param(key), str(lst))
                    res_str += '取得[' + str(lst)[0: 35] + '...' + ']==>[${' + key + '}];'
                return True, res_str
            elif isOK is False:
                return isOK, '执行MDX失败，具体原因：【{}】'.format(result)
        else:
            return isOK, '执行MDX失败，具体原因：【{}】'.format(result)

    def execut_sqlserver(self, **kwargs):
        """
        执行SQLServerSql
        :param kwargs:
        :return:
        """
        try:
            sql = kwargs['f_params']
        except KeyError:
            return False, '【执行SQLServerSql】执行失败：方法缺少【参数一】SQL语句，执行失败'
        try:
            var = kwargs['result']
            par = kwargs['s_params']
        except Exception:
            var = None
        if (var == '' and par != '') or (var != '' and par == ''):
            return False, '【执行SQLServerSql】执行失败：方法【变量】与【参数二】，必须都填或都不填，不能只填一个'
        if var == '':
            var = None
        try:
            dbn = kwargs['t_params']
        except KeyError:
            dbn = None
        env_id = kwargs['envid']
        isOK, result = self.manage.get_data_conf_info(env_id, 4, dbn)  # 1代表是mysql, 获取sql的数据库
        if isOK:
            sql = self.mangerattr.replace_data(sql)
            isOK, result = self.operatordb.excetSql(sql, **result)
            if isOK and var is not None:
                data = str(result[par])
                self.mangerattr.setattr(analyzing_param(var), data)
                return True, '执行SQLServerSql:[' + sql + ']成功，取得' + par + '的数据[' + data + ']==>[${' + var + '}]'
            elif isOK and var is None and (
                    'insert' in sql.lower() or 'update' in sql.lower() and 'update_time' not in sql.lower()):
                return True, '执行SQLServerSql:[' + sql + ']成功'
            elif isOK and var is None:
                res_str = '执行SQLServerSql:[' + sql + ']成功;;'
                for key, value in result.items():
                    self.mangerattr.setattr(key, str(value))
                    res_str += '取得[' + str(value) + ']==>[${' + key + '}];'
                return True, res_str
            elif isOK is False:
                return isOK, '执行SQLServerSql失败，具体原因：【{}】'.format(result)
        else:
            return isOK, '执行SQLServerSql失败，具体原因：【{}】'.format(result)

    # kwars = {}
    # kwars['db'] = 'http://172.56.20.48:10411/api/v1/ExecuteMDX?$expand=Cells($select=*)'
    # kwars['dbuser'] = 'admin'
    # kwars['dbpwd'] = 'apple'
    # kwars[
    #     'data'] = '{"MDX":"Select {[组织_楼栋].[集团].children} ON ROWS,{[产品].members} ON COLUMNS From [C0100_楼栋产品映射] Where ([情景].[启动会],[版本].[工作版])"}'
    # word = 'Ordinal,FormatString,FormattedValue,Updateable'
    # kwars['db'] = kwars['db'].replace('*', word)
    # obj = OpeartorDB()
    # result = obj.get_ibmcdata(**kwars)
    # res = result.json()['Cells']
    # lst_format = []
    # for r in res:
    #     lst_format.append(float(r['FormatString']))
    #
    # formatstring = str(lst_format)
    # print(formatstring)

    def send_email(self, **kwargs):
        """
        发送邮件
        :return:
        """
        return self.sendMail.send_email()


    def send_msg(self, **kwargs):
        """
        发送消息
        :param kwargs:
        :return:
        """
        title = kwargs['title']
        url = kwargs['url']
        type = kwargs['type']
        code = kwargs['code']
        result = kwargs['result'].encode('utf-8').decode('unicode_escape')
        nowTime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')  # 现在
        msg = nowTime + '\n用例名称：' + title + '\n请求：' + url + '\n类型：' + type + '\n响应码：' + code + '\n响应信息：' + \
              result + '\n\n[此为测试不通过的接口，请及时检查；由于参数过于长未在通知消息中展示，具体详情测试报告请查收钉钉邮件report.html附件，附件须下载，以谷歌浏览器打开]'
        if self.msyType == 'wechat':
            self.sedMsg.sendMsg(msg)
        else:
            self.dingMsg.sendMsg(msg)


    def time_factory(self, **kwargs):
        """
        获取时间
        :param kwargs: dict par
        :return: True or False  and result
        """
        try:
            var = kwargs['result']
            par = kwargs['f_params']
            try:
                part = kwargs['s_params']
                if part == '':
                    part = 0
                else:
                    part = int(part)
            except :
                part = 0
        except KeyError:
            return False, '【获取时间】执行失败：方法缺少参数'
        if var == '':
            return False, '【获取时间】执行失败：方法缺少【变量】'

        if par == 'd':
            param = (datetime.datetime.now()+datetime.timedelta(days=part)).strftime('%Y-%m-%d')

        elif par == 't':
            param = (datetime.datetime.now()+datetime.timedelta(seconds=part)).strftime('%Y-%m-%d %H:%M:%S')
        else:
            param = str(int((datetime.datetime.now()+datetime.timedelta(seconds=part)).timestamp()*1000))
        self.mangerattr.setattr(analyzing_param(var), param)
        return True, ' 已经将时间数据[' + param + ']==>[${' + var + '}]'


    def fromJsongetparlist(self, **kwargs):
        """
        JSON结果取某字段列表
        """
        try:
            avr = json.loads(kwargs['result'])
            par = kwargs['f_params']
        except Exception:
            return False, '方法缺少参数或JSON数据格式有误，执行失败'
        params = '$..' + par
        lst = jsonpath.jsonpath(avr, params)

        if lst is False:
            return False, 'json串result中没有字段【' + par + '】的值'
        return True, lst


    def replace_data(self, **kwargs):
        """
        逆参数化
        """
        try:
            par = kwargs['par']
        except Exception as e:
            return False, '传参失败，具体原因请看{}'.format(str(e))
        return True, self.replacedata(data=par)[1]


    def generate_chinese_characters(self, **kwargs):
        """
        生成中文字符串
        f_params:数量，中文的个数
        """
        try:
            res = kwargs['result']
            try:
                f_params = int(kwargs['f_params'])
            except Exception as e:
                f_params = 6
        except Exception as e:
            return False, '【生成中文字符串】执行失败：方法缺少参数'
        if res == '':
            return False, '【生成中文字符串】执行失败：方法缺少【变量】'
        chinese = """梁国一户姓杨的人家家里有一个九岁的儿子未闻孔雀是夫子家禽结客少年场隔花遥劝酒偷嫁汝南王衡山有三峰极秀湘东有雨母山小酉山石穴中富阳东南七十里江陵有潜室辄有兵寇俎豆非所习应为万里侯自怜才智尽空伤年鬓秋要是说散文取材十分广泛自由作者借助想象与联想论述散文创作的某种特色所惯常运用的提法线索的类型及其在具体文章中的表现形式是多种多样的"""
        chinese_characters = list(chinese)
        ranstr = ''.join(random.sample(chinese_characters, f_params)).replace(' ', '').replace('\n', '')   #不知道为啥，总有空字符串与回车影响
        self.mangerattr.setattr(analyzing_param(res), ranstr.encode("unicode_escape"))
        return True, ' 已经生成中文字符串['+ ranstr + ']==>[${' + res + '}]'



    def generate_english_abc(self, **kwargs):
        """
        生成英文字符串
        f_params:
        数量，
        中文的个数，
        大小写, u大写，l小写，ul混合
        """
        try:
            res = kwargs['result']
            try:
                f_params = int(kwargs['f_params'])
            except KeyError:
                f_params = 6
            try:
                s_params = str(kwargs['s_params'])
            except KeyError:
                s_params = 'l'
        except KeyError:
            return False, '【生成英文字符串】执行失败：方法缺少参数'
        if res == '':
            return False, '【生成英文字符串】执行失败：方法缺少【变量】'
        english = """abcdefghijklmnopqrstuvwxyz"""
        if str.lower(s_params) == 'u':
            english_abc = list(str.upper(english))
        elif str.lower(s_params) == 'ul':
            english_abc = list(str.upper(english) + english)
        else:
            english_abc = list(english)
        ranstr = ''.join(random.sample(english_abc, f_params)).replace(' ', '').replace('\n', '')   #不知道为啥，总有空字符串与回车影响
        self.mangerattr.setattr(analyzing_param(res), ranstr.encode("unicode_escape"))
        return True, ' 已经生成英文字符串[' + ranstr + ']==>[${' + res + '}]'



    def generate_identity_card(self, *args, **kwargs):
        """
        生成一个身份证号
        param=None, addr=None, year=None
        :param param: 变量名
        :param addr: 地区地址
        :param year: 年份
        :return:
        """
        try:
            param = kwargs['result']
        except KeyError:
            param = None
        try:
            addr = kwargs['f_params']
        except KeyError:
            addr = None
        try:
            year = kwargs['s_params']
        except KeyError:
            year = None

        # 获取地区编号
        xlsx = Readexcel('addrcode.xlsx', 'addrcode')
        addrCode = xlsx.read_excels()
        if addr is None or addr == '':
            a = random.sample(addrCode, 1)[0]
        else:
            pass  # 取出addr的那一列来用，等待完善
        _code = str(a['code'])

        # 随机取年分
        if year is None or year == '':
            year = random.randint(1949, 2020)
        else:
            year = int(year)
        _year = str(year)

        # 随机取月分完善格式
        mo = random.randint(1, 12)
        if mo < 10:
            _month = '0' + str(mo)
        else:
            _month = str(mo)

        # 通过日历规则随机取日期
        if mo < 8 and mo != 2 and mo % 2 == 1 or mo >= 8 and mo % 2 == 0:
            day = random.randint(1, 31)
        elif mo != 2:
            day = random.randint(1, 30)
        elif year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
            day = random.randint(1, 29)
        else:
            day = random.randint(1, 28)
        if day < 10:
            _day = '0' + str(day)
        else:
            _day = str(day)

        # 随机取倒数2~4位数字
        _randint = str(random.randint(100, 999))

        # 计算出最后一位数字
        _17code = _code + _year + _month + _day + _randint
        sumC = 0
        wi = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2]
        se = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2']
        c = 0
        for i in _17code:
            sumC += int(i) * wi[c]
            c += 1
        count = sumC % 11
        _last = se[count]
        id_card = _17code + _last
        if param is None or param == '':
            self.mangerattr.setattr('idcard', id_card)
            _strLog = '已生成身份证号码[' + id_card + ']==>' + '[${idcard}]'
        else:
            self.mangerattr.setattr(analyzing_param(param), id_card)
            _strLog = '已生成身份证号码[' + id_card + ']==>' + '[${' + param + '}]'
        return True, _strLog



    def str2key(self, s):
        # 对字符串解码
        b_str = base64.b64decode(s)

        if len(b_str) < 162:
            return False

        hex_str = ''

        # 按位转换成16进制
        for x in b_str:
            h = hex(x)[2:]
            h = h.rjust(2, '0')
            hex_str += h

        # 找到模数和指数的开头结束位置
        m_start = 29 * 2
        e_start = 159 * 2
        m_len = 128 * 2
        e_len = 3 * 2

        modulus = hex_str[m_start:m_start + m_len]
        exponent = hex_str[e_start:e_start + e_len]

        return modulus, exponent

    def rsa_encrypt(self, **kwargs):
        '''
         rsa加密
        :param s:
        :param pubkey_str:公钥
        :return:
        '''

        try:
            param = kwargs['result']
            f_params = kwargs['f_params']
            s_params = kwargs['s_params']
        except KeyError:
            return False, "【rsa加密】执行失败，参数没给齐"
        if param == '' or f_params == '' or s_params == '':
            return False, "【rsa加密】执行失败，参数没给齐"

        if len(param.split(';')) == 2:
            result = param.split(';')
            result[0] = analyzing_param(result[0])
            result[1] = analyzing_param(result[1])
        else:
            return False, "rsa加密】执行失败，两个变量需要以分号';'分割"

        _isOK, api = self.replacedata(data='${resapi}')
        if api == '${resapi}':
            api = '/apig/sys/v1/api/token/rsa/commonkey'
        url = parse.urljoin(self.replacedata(data='${host}')[1], api)
        response = requests.get(url=url)
        pubkey_str = jsonpath.jsonpath(response.json(), '$..data')[0]
        key = self.str2key(pubkey_str)
        modulus = int(key[0], 16)
        exponent = int(key[1], 16)
        pubkey = rsa.PublicKey(modulus, exponent)
        f_value = base64.b64encode(rsa.encrypt(self.replacedata(data=f_params)[1].encode(), pubkey)).decode()
        s_value = base64.b64encode(rsa.encrypt(self.replacedata(data=s_params)[1].encode(), pubkey)).decode()
        self.mangerattr.setattr(result[0], f_value)
        self.mangerattr.setattr(result[1], s_value)
        _strLog = '密文[' + f_value + ']==>' + '[${' + result[0] + '}]; 密文[' + s_value + ']==>' + '[${' + result[1] + '}]'
        return True, _strLog


    def clearParams(self, **kwargs):
        """
        清楚临时变量
        """
        return self.mangerattr.delattrs()

    def replacedata(self, **kwargs):
        """
        replacedata:参数数据获取
        data: 里面带有${}变量的字符串
        """
        try:
            data = kwargs['data']
        except Exception:
            return False, '没有带参数'
        return True, self.mangerattr.replace_data(data)

    def reGetrulepar(self, **kwargs):
        '''
        正则取值
        f_params: 目标字符串
        s_params: 正则规则
        '''

        try:
            isOK, result = self.replacedata(data=kwargs['result'])
            isOK, f_params = self.replacedata(data=kwargs['f_params'])
            s_params = r'{}'.format(kwargs['s_params'])     #用r防止一些系统的\t类的字符被转译
        except Exception as e:
            return False, '【正则取值】执行失败，参数异常，具体为：[{}]'.format(str(e))
        if result == '' or f_params == '' or s_params == '':
            return False, '【正则取值】执行失败:参数没给齐'


        try:
            if re.search(s_params, f_params): #判断有没有
                res = re.search(s_params, f_params)  #获取对像
                resul = res.group(1)  #取第一个
                print(resul)
            else:
                return False, '在{}中通过正则表达式{}未能获取到值，请检查用例'.format(f_params, s_params)
        except Exception as e:
            return False, '正则表达式编写有误，具体原因[{}],请检查用例'.format(str(e))
        self.mangerattr.setattr(result, resul)
        return True, '已通过正则表达式获取[{}]=>[{}]'.format(resul, result)

    def get_PhoneNumber(self, **kwargs):
        '''
        随机手机号
        获取一个随机生成的手号码
        '''
        try:
            isOK, result = self.replacedata(data=kwargs['result'])
            if isOK is False or result == '':
                return False, '【随机手机号】执行失败：没给【变量】'
        except Exception as e:
            return False, '参数异常，具体为：[{}]'.format(str(e))

        p_header = """135、136、137、138、139、150、151、152、158、159、182 、183、184、187、188、147、178、130、131、132、155、156、185、186、145、176、180、181、189、133、153、177"""
        p_lst = p_header.split('、')
        p_Nb = random.choice(p_lst)
        ps_lst = list('1234567890')
        p_Nb += ''.join(random.sample(ps_lst, 8))
        self.mangerattr.setattr(result, p_Nb)
        return True, '已随机生成手机号码[' + p_Nb + ']==>[${' + result + '}]'

    def get_randonNo(self, **kwargs):
        '''
        随机数字
        获取一个随机生成的手号码
        '''
        try:
            isOK, result = self.replacedata(data=kwargs['result'])
            if isOK is False or result == '':
                return False, '【随机数字】执行失败：没给【变量】'
            isOK, f_params = self.replacedata(data=kwargs['f_params'])
            if isOK is False or f_params == '':
                f_params = 8
        except Exception as e:
            return False, '参数异常，具体为：[{}]'.format(str(e))
        ps_lst = list('1234567890')
        ranNo = ''.join(random.sample(ps_lst, int(f_params)))
        self.mangerattr.setattr(result, ranNo)
        return True, '已随机生成数字[' + ranNo + ']==>[${' + result + '}]'

# com = CommKeyword()
# isOK, result = com.get_randonNo(result='abc', f_params=10)
# print(result)

#调试正则表达式
# aaa = '/flow/panel-other.html#/msgView/process/todo-handle?id=8344&taskId=4c38ab9498d04dff8622bcf39ded3c05&contentId=4c38ab9498d04dff8622bcf39ded3c05&msgId=8c2addafb5514f789ce2d09f8dcc610e&appCode=bpm'
# rule =  '\?id=(.*?)\&'
# com = CommKeyword()
# com.reGetrulepar(result='abc', f_params=aaa, s_params=rule)
# rele = 'taskId=(.*?)\&'
# com.reGetrulepar(result='abc', f_params=aaa, s_params=rele)

